<template>
  <!-- 移动平台终端列表 -->
  <div class="TerminalList">
    <el-table :data="list" style="width: 100%" v-if="!this.userType.includes('terminal')">
      <el-table-column type="index" label="序号" width="150" align="center" />
      <el-table-column prop="name" :label="`${Terminal.name}名称`" align="center" />
      <el-table-column prop="id" label="终端编号" align="center" />
      <el-table-column prop="manager" label="管理人" align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click.stop="choiceClick(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="this.userType.includes('terminal')">
      <span class="title">{{ Terminal.name }}名称：<el-input v-model="nowTermina" readonly /></span>
      <span class="title">终端编号：<el-input v-model="id" readonly /></span>
      <span class="title">管理人：<el-input v-model="manager" readonly /></span>
      <p style="display: inline-block;">
        <span class="title" v-if="!this.userType.includes('terminal')">当前{{ Terminal.name }}：</span>
        <el-input v-if="!this.userType.includes('terminal')" v-model="nowTermina" :placeholder="`请选择需要查看的${Terminal.name}`" style="width:3rem;margin-right:0.2rem;" readonly />
        <span class="title">素材提交时间：</span>
        <el-date-picker v-model="form.submitTimeStr" class="searchItem" type="month" placeholder="选择月" format="yyyy年MM月" value-format="yyyy年MM月" :picker-options="pickerBeginMonth" />
        <el-button type="primary" @click="searchClick()" style="margin-left:0.2rem;">查询</el-button>
      </p>
    </div>
    <p v-else style="display: inline-block;">
      <span class="title" v-if="!this.userType.includes('terminal')">当前{{ Terminal.name }}：</span>
      <el-input v-if="!this.userType.includes('terminal')" v-model="nowTermina" :placeholder="`请选择需要查看的${Terminal.name}`" style="width:3rem;margin-right:0.2rem;" readonly />
      <span class="title">素材提交时间：</span>
      <el-date-picker v-model="form.submitTimeStr" class="searchItem" type="month" placeholder="选择月" format="yyyy年MM月" value-format="yyyy年MM月" :picker-options="pickerBeginMonth" />
      <el-button type="primary" @click="searchClick()" style="margin-left:0.2rem;">查询</el-button>
    </p>
    <div class="content">
      <el-table ref="materialTable" :data="materialList" style="width: 100%;" v-loading="loading">
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column label="数据类别" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.materialType | dataFormate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="approveProcess" label="流程审批类别" align="center" width="180" />
        <el-table-column prop="materialName" label="数据名称" align="center" :show-overflow-tooltip="true" />
        <el-table-column label="预发布终端类别" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.terminalType | terminaFormate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="submitter" label="提交人" align="center" width="150" />
        <el-table-column prop="submitTime" label="提交时间" align="center" width="150" />
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="buttonClick(scope.$index, scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          popper-class="DataAcquisition_fenye"
          :current-page="form.pageNum"
          background
          :page-sizes="[10, 20, 30, 40]"
          :page-size="form.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog :title="dataTitle" :visible.sync="Playvideo" center class="videoDialog" @close="closeVideo">
      <player :video-url="previewUrl" :state="Playvideo" />
    </el-dialog>
    <el-dialog :title="dataTitle" :visible.sync="Playvoice" center @close="closeVoice">
      <voice-Play :title="dataTitle" :src="previewUrl" :state="Playvoice" />
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import store from '../../../store'
import player from '@/components/VideoPlay'
import VoicePlay from '@/components/VoicePlay'
export default {
  name: 'TerminalList',
  components: { player, VoicePlay },
  data() {
    return {
      list: [],                     // 终端列表
      type: '',                     // 终端类别
      nowTermina: '',               // 当前终端类型
      id: '',                       // 终端编码
      manager: '',                  // 终端管理员
      total: 0,                     // 分页器数据总数
      form: {
        terminalId: '',             // 终端ID
        terminalType: 'ydList',     // 终端类型（固定参数）
        processState: 4,            // 任务状态（固定参数）
        submitTimeStr: '',          // 查询时间
        pageNum: 1,                 // 当前页
        pageSize: 10                // 每页数据条目
      },
      materialList: [],             // 具体某一终端下，查询出的具体素材列表
      pickerBeginMonth: {
        disabledDate(time) {
          const befor = time.getFullYear() < new Date('2019').getFullYear()
          const after = time.getTime() > Date.now()
          return befor || after // 设置早于当前年份，晚于当前时间的月份不可选择
        }
      },
      userType: '',        // 用户登录类型（后台管理/终端登录）
      loading: false,
      dataTitle: '',       // 素材标题
      Playvideo: false,    // 视频
      Playvoice: false,    // 音频
      previewUrl: ''       // 素材详情url
    }
  },
  computed: {
    Terminal() {
      const data = JSON.parse(sessionStorage.getItem('Terminal'))
      this.type = data.key
      this.form.terminalType = data.key
      return data
    }
  },
  created() {
    // 请求终端列表
    this.userType = store.getters.roles
    if (this.userType.includes('terminal')) {
      // 当前登录为终端登录，请求当前登录终端对应列表
      this.form.terminalId = getToken()
      this.getTerminal_one()
    } else {
      this.getTerminal()
    }
    // 默认搜索时间
    const pad = n => (n < 10 ? `0${n}` : n)
    const date = new Date()
    const yyyyMM = `${date.getFullYear()}年${pad(date.getMonth() + 1)}月`
    this.form.submitTimeStr = yyyyMM
  },
  methods: {
    // 请求全量移动终端
    getTerminal() {
      this.$api.getTerminalList().then((response) => {
        if (response.data.status == 1) {
          this.list = response.data.data[this.type]
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    // 终端登录时，仅请求当前登录终端的数据
    getTerminal_one() {
      this.$api.getTerminalPreview({id: getToken()}).then((response) => {
        if (response.data.status == 1) {
          this.list = response.data.data
          this.nowTermina = this.list[0].name
          this.id = this.list[0].id
          this.manager = this.list[0].manager
          this.searchClick()
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    // 选择终端 
    choiceClick(data) {
      this.nowTermina = data.name
      this.form.terminalId = data.id
    },
    // 查询
    searchClick() {
      this.loading = true
      this.$api.getTerminalMaterial(this.form).then((response) => {
        this.materialList = []
        if (response.data.status == 1) {
          setTimeout(() => {
            this.loading = false
            this.materialList = response.data.data.list
            this.total = response.data.data.list.length
          }, 500);
        } else {
          setTimeout(() => {
            this.loading = false
            this.$message.error(response.data.msg)
          }, 500);
        }
      })
    },
    // 操作
    buttonClick(index, data) {
      let key = data.materialType
      switch (key) {
        case 'news':
          sessionStorage.setItem('localRouter', '/TerminalPreview/terminal/terminalDetails')
          sessionStorage.setItem('materialId', data.materialId)
          setTimeout(() => {
            this.$router.push('/TerminalPreview/terminal/terminalDetails')
          }, 100);
          break;
        case 'image':
          this.$api.getDataDetails({id: data.materialId}, key).then((response) => {
            if (response.data.status == 1) {
              let file = response.data.data.mediaFile
              window.open(file.uploadUrl, '_blank')
            }
          })
          break;
        case 'file':
          this.$api.fileDownload({ id: data.materialId }).then((response) => {
            const blobUrl = window.URL.createObjectURL(response.data)
            const link = document.createElement('a')
            document.body.appendChild(link)
            link.style.display = 'none'
            link.href = blobUrl
            // 设置a标签的下载属性，设置文件名及格式，后缀名最好让后端在数据格式中返回
            link.download = data.materialName
            // 自触发click事件
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(blobUrl)
          })
          break;
        case 'web':
          this.$api.htmlListDetail({id: data.materialId}).then((response) => {
            if (response.data.status == 1) {
              let res = response.data.data.mediaWeb
              window.open(res.url, '_blank')
            }
          })
          break;
        default: // voice/vedio
          this.$api.getDataDetails({id: data.materialId}, key).then((response) => {
            if (response.data.status == 1) {
              let file = response.data.data.mediaFile
              this[`Play${key}`] = true
              this.dataTitle = file.fileName
              this.previewUrl = file.uploadUrl
            }
          })
          break;
      }
    },
    // 关闭视频
    closeVideo() {
      this.Playvideo = false
      this.dataTitle = ''
      this.previewUrl = ''
    },
    // 关闭音频
    closeVoice() {
      this.Playvoice = false
      this.dataTitle = ''
      this.previewUrl = ''
    },
    // 改变每页数据条目数
    handleSizeChange(val) {
      this.form.pageSize = val
      this.searchClick()
    },
    // 当前第几页
    handleCurrentChange(val) {
      this.form.pageNum = val
      this.searchClick()
    },
  }
}
</script>
<style lang="scss" scoped>
.TerminalList {
  width: 100%;
  background: #fff;
  padding: 0.2rem;
  border-radius: 0.05rem;
  -webkit-box-shadow: #ccc 0 0 10px 0px;
  box-shadow: #ccc 0 0 10px 0px;
  .title {
    font-size: 0.16rem;
    .el-input {
      width: 2rem;
      margin-right: 0.2rem;
      font-size: 0.2rem;
      font-weight: bold;
    }
  }
  .content {
    padding: 0.2rem;
    min-height: 5rem;
    border-bottom: 1px solid #ccc;
    position: relative;
    overflow: hidden;
    .terminal {
      background: #F8F8F8;
      padding: 0.1rem 0.2rem;
      min-height: 2rem;
    }
    .pagination {
      width: 100%;
      background: #fff;
      text-align: right;
      padding-top: 0.2rem;
    }
  }
  .videoDialog {
    >>>.el-dialog {
      border-radius: 0.1rem;
      overflow: hidden;
      .el-dialog__header {
        padding: 0;
        height: 0.5rem;
        background-image: linear-gradient(0deg, #1E242C 0%,rgba(30, 36, 44, .85) 30%, #1E242C 100%);
        .el-dialog__title {
          font-size: 0.2rem !important;
          line-height: 0.51rem;
          color: #fff;
        }
        .el-dialog__headerbtn {
          top: 0.11rem;
          right: 0.2rem;
          .el-dialog__close {
            color: #fff;
            font-size: 0.3rem !important;
          }
        }
      }
      .el-dialog__body {
        background: #1E242C;
        padding: 0.1rem;
      }
    }
  }
}
</style>
